package algorithm.leetcode;

/**
 * @program: util
 * @description:最长公共前缀，拿出第一个来依次与后边的元素挨个比较
 * @author: zhouliangliang
 * @create: 2021-04-12 20:24
 **/
public class LonggestPublicPrefix {


    private String  solve(String []str) {
        int index = 0;
        while (index < str[0].length()) {
            Character c = str[0].charAt(index);
            boolean isequal = equal(str, c, index);
            if(isequal) {
                index ++;
            } else {
                break;
            }
        }
        return str[0].substring(0, index);
    }

    /**
     * 判断数组中每一个字符串在index位置的字符是否等于c
     * @param str
     * @param c
     * @param index
     * @return
     */
    private boolean equal(String []str, Character c, int index) {
        for(int i=1; i<str.length; i++) {
            if( (str[i].length()-1 < index)  ||  (str[i].charAt(index) != c)) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String [] array = new String[]{"abc","abce","abcf","abcbc"};
        new LonggestPublicPrefix().solve(array);
    }
}
